/*******************************************************************************
 * Copyhacked (H) 2012-2025.
 * This program and the accompanying materials
 * are made available under no term at all, use it like
 * you want, but share and discuss it
 * every time possible with every body.
 * 
 * Contributors:
 *      ron190 at ymail dot com - initial implementation
 ******************************************************************************/
package com.jsql.view.swing.terminal;

import com.jsql.util.LogLevelUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.UUID;

/**
 * A terminal for web shell injection.
 */
public class ExploitReverseShell extends AbstractExploit {

    private static final Logger LOGGER = LogManager.getRootLogger();

    private final transient ServerInput serverInput;

    /**
     * Build a webshell instance.
     *
     * @param terminalID Unique identifier to discriminate beyond multiple opened terminals
     * @param port
     */
    public ExploitReverseShell(UUID terminalID, String port) throws IOException, URISyntaxException {
        super(terminalID, null, "reverse", false);

        this.serverInput = new ServerInput(this, Integer.parseInt(port));
        new Thread(() -> {
            try {
                this.serverInput.startServer();
            } catch (IOException e) {
                try {
                    LOGGER.log(LogLevelUtil.CONSOLE_ERROR, "Socket connection failure: {}", e.getMessage());
                    this.serverInput.close();
                } catch (IOException ex) {
                    LOGGER.log(LogLevelUtil.CONSOLE_ERROR, "Socket closing failure: {}", ex.getMessage());
                }
            }
        }).start();
    }

    @Override
    public void action(String command, UUID terminalID, String urlShell, String... arg) {
        this.serverInput.getServerInputConnection().setCommand(command);
    }
}
